package handler

import (
	"car-trade-mgr/model"
	"github.com/gin-gonic/gin"
	"strconv"
)

func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.RNis{
		Rid: rid,
		Nid: nid,
	}
	var roleNode model.RNis
	err := model.DB.Create(&data).Find(&roleNode).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "分配失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
	})
	return
}

func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	var role []model.Role
	/*
		SELECT
		*
		FROM
		roles
		LEFT JOIN u_ris ON u_ris.rid=roles.id
		WHERE u_ris.uid=1
	*/
	model.DB.Table("roles").
		Joins("LEFT JOIN u_ris ON u_ris.rid=roles.id").
		Where("u_ris.uid=?", uid).
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": role,
	})
	return
}

func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	var node []model.Node
	/*
		SELECT
		*
		FROM
		nodes
		LEFT JOIN r_nis ON r_nis.nid=nodes.id
		WHERE r_nis.nid=1
	*/
	model.DB.Table("nodes").
		Joins("LEFT JOIN r_nis ON r_nis.nid=nodes.id").
		Where("r_nis.rid=?", rid).
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": node,
	})
	return
}
